<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { User, Lock } from '@element-plus/icons-vue';
import { userRegisterService, userLoginService } from '@/api/admin.js'
import router from '@/router';
import { useUserStore } from '@/stores/admin'; // 添加这行
import { nextTick } from 'vue';

const userStore = useUserStore(); // 初始化 userStore

const form = ref();
const isRegister = ref(false);
const twostep = ref(false);
const formModel = ref({
    username: '',
    password: '',
    repassword: '',
    phonenumber: '',
    code: '',
    newpassword: ''
});

const register = async () => {
  // 注册成功之前，先进行校验，校验成功 → 请求，校验失败 → 自动提示
  try{ 
    await form.value.validate()
    const response = await userRegisterService({
    username: formModel.value.username, 
    password: formModel.value.password
  })
  if (response.data.code === '0000') {
      ElMessage.success('注册成功');
      isRegister.value = false;
    } else {
      ElMessage.error(response.data.msg || '注册失败');
    }
  } catch (error) {
    // 捕获并处理错误
    console.error('注册错误:', error);
    ElMessage.error(error.response?.data?.msg || '注册过程中发生错误');
  }
}

// LoginPage.vue
const login = async () => {
  try {
    await form.value.validate()
    const res = await userLoginService({
      username: formModel.value.username,
      password: formModel.value.password
    })
    
    if (res.data.code === '0000') {
      // 1. 先存储 token
      userStore.setToken(res.data.data)
      
      // 2. 等待用户信息获取完成
      try {
        await userStore.getUser()
        
        // 3. 添加一个小延迟确保状态完全更新
        await new Promise(resolve => setTimeout(resolve, 100))
        
        ElMessage.success('登录成功')
        router.push('/home')
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 即使获取用户信息失败，也允许跳转
        ElMessage.success('登录成功')
        await nextTick()
        setTimeout(() => {
        router.push('/')
      }, 300)
      }
    } else {
      ElMessage.error(res.data.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error(error.response?.data?.msg || '登录过程中发生错误')
  }
}


watch(isRegister,()=>{
    formModel.value.username = '';
    formModel.value.password = '';
    formModel.value.repassword = '';
    formModel.value.phonenumber = '';
    formModel.value.code = '';
    formModel.value.newpassword = '';
})

const rules={
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    repassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
        { validator: (rule, value) => {
            if (value !== formModel.value.password) {
                return new Error('两次输入密码不一致');
            }
            return true;
        }, trigger: 'blur' }
    ],
    phonenumber: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 6, message: '验证码为6位数字', trigger: 'blur' }
    ],
    newpassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ]
};
</script>


<template>
    <el-row class="login-page">
        <el-col :span="12" class="bg"></el-col>
        <el-col :span="6" :offset="3" class="form">
            <el-form 
                :model="formModel" 
                :rules="rules" 
                ref="form" 
                size="large" 
                autocomplete="off"
                v-if="isRegister"
            >
                <el-form-item>
                <h1>注册</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input v-model="formModel.username" placeholder="请输入用户名" :prefix-icon="User"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="formModel.password" type="password" placeholder="请输入密码" :prefix-icon="Lock"></el-input>
                </el-form-item>
                <el-form-item prop="repassword">
                    <el-input v-model="formModel.repassword" type="password" placeholder="请再次输入密码" :prefix-icon="Lock"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="register" class="button" type="primary" auto-insert-space>注册</el-button>
                </el-form-item>   
                <el-form-item>
                    <el-link type="info" @click="isRegister = false" :underline="false">返回</el-link>
                </el-form-item>
            </el-form>

            <el-form 
                :model="formModel" 
                :rules="rules" 
                ref="form" 
                size="large" 
                autocomplete="off"
                v-if="!isRegister&&!twostep"
            >
                <el-form-item>
                <h1>登录</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input v-model="formModel.username" placeholder="请输入用户名" :prefix-icon="User"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="formModel.password" type="password" placeholder="请输入密码" :prefix-icon="Lock" show-password></el-input>
                </el-form-item>
                <el-form-item class="flexbetween">
                    <el-checkbox>记住我</el-checkbox>
                    <el-link type="primary" @click="twostep = true" :underline="false">忘记密码？</el-link>
                </el-form-item>
                <el-form-item>
                    <el-button plain="true" @click="login" class="button" type="primary" auto-insert-space>登录</el-button>
                </el-form-item>   
                <el-form-item class="flex">
                    <el-link type="info" @click="isRegister = true" :underline="false">注册</el-link>
                </el-form-item>
            </el-form>
            
            <el-form 
                :model="formModel" 
                :rules="rules" 
                ref="form" 
                size="large" 
                autocomplete="off"
                v-if="!isRegister&&twostep"
            >
                <el-form-item>
                <h1>找回密码</h1>
                </el-form-item>
                <el-form-item prop="phonenumber">
                    <el-input v-model="formModel.phonenumber" placeholder="请输入手机号" :prefix-icon="User"></el-input>
                </el-form-item>
                <el-form-item prop="code">
                    <el-input v-model="formModel.code" type="password" placeholder="请输入验证码" :prefix-icon="Lock"></el-input>
                </el-form-item>
                <el-form-item prop="newpassword">
                    <el-input v-model="formModel.newpassword" type="password" placeholder="请输入新密码" :prefix-icon="Lock"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="ElMessage.success('新密码确认完毕！')" class="buttton" type="primary" auto-insert-space>确认新密码</el-button>
                </el-form-item>   
                <el-form-item>
                    <el-link type="info" @click="twostep = false" :underline="false">返回</el-link>
                </el-form-item>
            </el-form>

        </el-col>
    </el-row>
</template>

<style lang="scss" scoped>
.login-page{
    height: 100vh;
    .bg{
        background: url('@/assets/login-bg.jpg') no-repeat center;
        background-size: cover;
    }
    .form{
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        h1{
            text-align: center;
            margin-bottom: 20px;
            font-weight: bold;
            color: #409EFF;
        }
        .button{
            width: 100%;
        }
        .flex{
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .flexbetween {
            display: flex;
            justify-content: space-between; /* 关键：让两个元素分别靠左右对齐 */
            align-items: center;
        }
    }
}
</style>